package com.geek.javase.ch13.work.deepclone;

import java.io.*;

/*
 *@author wangpeng
 *2025/10/27 21:17
 *@description TODO
 */

/**
 * 深克隆：建议方式，使用内存的字节流ByteArrayOutputStream和ByteArrayInputStream存储对象的字节序列，
 * 通过ObjectOutputStream和ObjectInputStream完成序列化和反序列化操作，从而达到深克隆的目的。
 */
//Cloneable 接口是一个标记接口，表明该类允许被克隆。
public class Person implements Cloneable, Serializable {
    private String name;
    private int age;
    //关联Phone类
    private Phone phone;

    /*@Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }*/
    /*@Override
    protected Person clone() throws CloneNotSupportedException {
        Person Person = (Person) super.clone();
        Person.phone = (Phone) phone.clone();
        return Person;
    }*/
    @Override
    protected Person clone() throws CloneNotSupportedException {
        try{
            //序列化
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(this);
            oos.flush();
            //反序列化
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);
            Person Person = (Person) ois.readObject();
            return Person;

        } catch (IOException |ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public Person(String name, int age, Phone phone) {
        this.name = name;
        this.age = age;
        this.phone = phone;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public Phone getPhone() {
        return phone;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setPhone(Phone phone) {
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", phone=" + phone +
                '}';
    }
}
